class AddPhotoData < ActiveRecord::Migration
  def self.up
    filenames = Dir.entries("db/migrate/data/")
    # puts filenames.size
    i = 2
    while i < filenames.size
      datalines = IO.readlines("db/migrate/data/" + filenames[i])
      # puts filenames[i]
      line = datalines[0].split(/\t/)
      #puts line
      #Create category
      directory = cleanString(line[8]) 
      category = Category.create(:name => line[0], :code => line[3].downcase, :description => cleanString(line[4]), :keywords => cleanString(line[9]))
      #Figure out which directory the images live in
      a = 1
      #Parse images
      while a < datalines.size
        line = datalines[a].split(/\t/)
        if (line[0] != nil && line[0].length != 0 && line[9] != "Y") then
          image = Image.create(:directory   => directory,
                               :filename    => fixFilename(line[0]),
                               :title1      => line[1],
                               :title2      => cleanString(line[2]),
                               :location    => cleanString(line[3]),
                               :shotdate    => cleanString(line[4]),
                               :description => cleanString(line[5]),
                               :camera      => cleanString(line[6]),
                               :lens        => cleanString(line[7]),
                               :forsale     => line[9],
                               :forlicense  => line[10],
                               :keywords    => cleanString(line[11]))
          CategoryImage.create(:category_id => category[:id], :image_id => image[:id], :order => a)
        end
        a = a + 1
      end
      i = i + 1
    end
  end

  def self.down
    CategoryImage.delete_all
    Image.delete_all
    Category.delete_all
  end

  private
    
  def self.cleanString(source)
    if source == "N/A" then
      source = nil
    elsif source.count("/thumb") > 0 then
      list = source.split(/thumb/)
      source = list[0]
    end
    source
  end
  
  def self.fixFilename(source)
    if source.index('jpg') == nil then
      source = source + '.jpg'
    end
    source
  end
end
